package guowei.guliauth.controller;

import com.alibaba.fastjson.TypeReference;
import guowei.common.constant.SessionInfo;
import guowei.common.utils.R;
import guowei.common.vo.MemberVo;
import guowei.guliauth.constant.SmsConstant;
import guowei.guliauth.feign.UserFeign;
import guowei.guliauth.vo.LoginVo;
import guowei.guliauth.vo.RegMemVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
public class RegAndLogin {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserFeign userFeign;

    @PostMapping("/registry")
    public String RegMember(@Valid RegMemVo regMemVo, BindingResult result, RedirectAttributes redirectAttributes){
        if (result.hasErrors()){

//      将后端检验到的错误信息，转为map发给前端
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            redirectAttributes.addFlashAttribute("errors",errors);

//      校验出错，重定向到注册页面
            return "redirect:http://auth.ganjiuwanle.com/reg.html";
        }

//      真正注册，调用远程服务 先检验验证码是否正确
        String code = regMemVo.getCode();   //传来的验证码
        String paramAndPhone = (String) redisTemplate.opsForValue().get(SmsConstant.SMS_PARAM_PREFIX + regMemVo.getPhone());
        if (StringUtils.isEmpty(paramAndPhone)){
            Map<String,String> map = new HashMap<String,String>();
            map.put("code","还没获取验证码呢");
            redirectAttributes.addFlashAttribute("errors",map);
            return "redirect:http://auth.ganjiuwanle.com/reg.html";
        }
        String param = paramAndPhone.split("_")[0];     //真正地验证码
        if (code.equals(param)){
            redisTemplate.delete(SmsConstant.SMS_PARAM_PREFIX + regMemVo.getPhone());
            R r = userFeign.regMem(regMemVo);
            if (r.getCode() == 0){
//                没异常就跳转登陆界面
                return "redirect:http://auth.ganjiuwanle.com/login.html";
            }else {
//                有异常就传给前端该异常
                Map<String,String> errors = new HashMap<String,String>();
                errors.put("msg", (String) r.get("msg"));
                redirectAttributes.addFlashAttribute("errors",errors);
                return "redirect:http://auth.ganjiuwanle.com/reg.html";
            }
        }else {
            Map<String,String> map = new HashMap<String,String>();
            map.put("code","验证码非常不正确，y重新输入");
            redirectAttributes.addFlashAttribute("errors",map);
            return "redirect:http://auth.ganjiuwanle.com/reg.html";
        }

    }

    /**
     * 普通登录和第三方登录一样，登陆得到的userinfo信息都存储在session中，而session的信息又存储在redis中
     * @param loginVo
     * @param redirectAttributes
     * @param session
     * @return
     */
    @PostMapping("/login")
    public String LoginMem(LoginVo loginVo, RedirectAttributes redirectAttributes, HttpSession session){
        R r = userFeign.LoginUser(loginVo);
        if (r.getCode() == 0){
            MemberVo memberVo = (MemberVo) r.getData("data", new TypeReference<MemberVo>() {});
            session.setAttribute(SessionInfo.SESSION_PREFIX,memberVo);
            return "redirect:http://ganjiuwanle.com";
        }else {
            Map<String,String> errors = new HashMap<>();
            errors.put("msg", (String) r.getData("msg",new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.ganjiuwanle.com/login.html";
        }
    }

    @GetMapping("/login.html")
    public String toLoginHtml(HttpSession session){
        Object attribute = session.getAttribute(SessionInfo.SESSION_PREFIX);
        if (attribute == null){
            return "login";
        }else {
            return "redirect://ganjiuwanle.com";
        }
    }

}